package net.homeip.jcperera.webinfo.beans;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import net.homeip.jcperera.nu.core.boot.Boot;
import net.homeip.jcperera.nu.core.msg.BaseMessage;
import net.homeip.jcperera.nu.core.msg.MessageBagRequest;
import net.homeip.jcperera.webinfo.WebInfoPattern;
import net.homeip.jcperera.webinfo.WebInfoSite;

import org.primefaces.event.SelectEvent;

@ManagedBean
@ViewScoped
public class WebInfoPatternBean implements Serializable
{
    private static final long serialVersionUID = -566051799699058355L;

    private WebInfoPattern    webInfoPattern;

    public WebInfoPatternBean()
    {
        webInfoPattern = new WebInfoPattern();
    }

    public List<WebInfoPattern> getWebInfoPatterns()
    {
        List<WebInfoPattern> webInfoPatterns = new ArrayList<WebInfoPattern>();
        if (webInfoPattern != null && webInfoPattern.getSite() != null)
        {
            webInfoPatterns.addAll(webInfoPattern.getSite().getWebinfopatterns());
        }
        return webInfoPatterns;
    }

    public void saveWebInfoPattern(ActionEvent actionEvent)
    {
        saveWebInfoPattern();
    }

    public String saveWebInfoPattern()
    {
        if (webInfoPattern != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            if (webInfoPattern.getEntityid() != null && webInfoPattern.getEntityid().length() > 0)
                webInfoPattern = entityManager.merge(webInfoPattern);
            entityManager.persist(webInfoPattern);
            entityManager.getTransaction().commit();
            entityManager.getEntityManagerFactory().getCache().evictAll();
            entityManager.close();
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            messageBagRequest.addInformationalMessage("nu.core.entity.saved.ok", BaseMessage.FRIENDLINESS_FRIENDLY);
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "edit.xhtml?faces-redirect=true&entityid=" + this.getEntityid();
    }

    public void deleteWebInfoPattern(ActionEvent actionEvent)
    {
        deleteWebInfoPattern();
    }

    public String deleteWebInfoPattern()
    {
        if (webInfoPattern != null)
        {
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            String entityid = webInfoPattern.getEntityid();
            if (entityid != null && entityid.trim().length() > 0)
            {
                EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
                EntityManager entityManager = (EntityManager) emf.createEntityManager();
                entityManager.getTransaction().begin();
                webInfoPattern = entityManager.merge(webInfoPattern);
                entityManager.remove(webInfoPattern);
                messageBagRequest.addInformationalMessage("nu.core.entity.deleted.ok",
                        BaseMessage.FRIENDLINESS_FRIENDLY);
                entityManager.getTransaction().commit();
                entityManager.getEntityManagerFactory().getCache().evictAll();
                entityManager.close();
            }
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "/pages/webinfosite/edit.xhtml?faces-redirect=true&entityid=" + this.getParentid();
    }

    public String getEntityid()
    {
        return webInfoPattern.getEntityid();
    }

    public void setEntityid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            WebInfoPattern webInfoPattern = null;
            TypedQuery<WebInfoPattern> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(wip) FROM WebInfoPattern wip WHERE wip.entityid = :entityid", WebInfoPattern.class);
            wisQuery.setParameter("entityid", entityid);
            webInfoPattern = wisQuery.getSingleResult();
            if (webInfoPattern == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.webInfoPattern = webInfoPattern;
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public String getParentid()
    {
        return ((webInfoPattern != null && webInfoPattern.getSite() != null) ? webInfoPattern.getSite().getEntityid()
                : null);
    }

    public void setParentid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            WebInfoSite webInfoSite = null;
            TypedQuery<WebInfoSite> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(wis) FROM WebInfoSite wis WHERE wis.entityid = :entityid", WebInfoSite.class);
            wisQuery.setParameter("entityid", entityid);
            webInfoSite = wisQuery.getSingleResult();
            if (webInfoSite == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.webInfoPattern.setSite(webInfoSite);
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public void onRowSelect(SelectEvent event)
    {
        try
        {
            FacesContext.getCurrentInstance().getExternalContext()
                    .redirect("../webinfopattern/edit.xhtml?entityid=" + webInfoPattern.getEntityid());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public WebInfoSite getSite()
    {
        return webInfoPattern.getSite();
    }

    public String getXslPattern()
    {
        return webInfoPattern.getXslPattern();
    }

    public void setXslPattern(String xslPattern)
    {
        webInfoPattern.setXslPattern(xslPattern);
    }

    public String getFormat()
    {
        return webInfoPattern.getFormat();
    }

    public void setFormat(String format)
    {
        webInfoPattern.setFormat(format);
    }

    public String getFieldName()
    {
        return webInfoPattern.getFieldName();
    }

    public void setFieldName(String fieldName)
    {
        webInfoPattern.setFieldName(fieldName);
    }

    public Boolean getIsPrimary()
    {
        return webInfoPattern.getIsPrimary();
    }

    public void setIsPrimary(Boolean isPrimary)
    {
        webInfoPattern.setIsPrimary(isPrimary);
    }

    public String getCreatedBy()
    {
        return webInfoPattern.getCreatedBy();
    }

    public Date getCreatedWhen()
    {
        return webInfoPattern.getCreatedWhen().getTime();
    }

    public String getModifiedBy()
    {
        return webInfoPattern.getModifiedBy();
    }

    public Date getMofifiedWhen()
    {
        return webInfoPattern.getModifiedWhen().getTime();
    }

    public long getLocalVersion()
    {
        return webInfoPattern.getLocalVersion();
    }

    public long getGlobalVersion()
    {
        return webInfoPattern.getGlobalVersion();
    }

    public void setSelectedWebInfoPattern(WebInfoPattern webInfoPattern)
    {
        this.webInfoPattern = webInfoPattern;
    }

    public WebInfoPattern getSelectedWebInfoPattern()
    {
        return this.webInfoPattern;
    }
}
